<!DOCTYPE html>
<html>
    <head>
        <title>Verify v2 events</title>
        <script src="encrypted-media-utils.js"></script>
        <script src="../../resources/testharness.js"></script>
        <script src="../../resources/testharnessreport.js"></script>
    </head>
    <body>
        <script>
            // Currently Clear Key only generates aynchronous "message" and
            // "keychange" events.
            async_test(function(test)
            {
                var initDataType;
                var initData;
                var mediaKeySession;
                var rawKey = new Uint8Array([0xeb, 0xdd, 0x62, 0xf1, 0x68, 0x14, 0xd2, 0x7b,
                                             0x68, 0xef, 0x12, 0x2a, 0xfc, 0xe4, 0xae, 0x3c]);

                function processMessage(event)
                {
                    assert_true(event instanceof window.MediaKeyMessageEvent);
                    assert_equals(event.target, mediaKeySession);
                    assert_equals(event.type, 'message');
                    assert_equals(event.messageType, 'license-request');

                    var keyId = extractSingleKeyIdFromMessage(event.message);
                    var jwkSet = stringToUint8Array(createJWKSet(createJWK(keyId, rawKey)));

                    waitForEventAndRunStep('keystatuseschange', mediaKeySession, test.step_func(processKeyStatusesChange), test);

                    mediaKeySession.update(jwkSet).catch(test.step_func(function(error) {
                        forceTestFailureFromPromise(test, error);
                    }));
                }

                function processKeyStatusesChange(event)
                {
                    assert_true(event instanceof Event);
                    assert_equals(event.target, mediaKeySession);
                    assert_equals(event.type, 'keystatuseschange');
                    test.done();
                }

                navigator.requestMediaKeySystemAccess('org.w3.clearkey', getSimpleConfiguration()).then(function(access) {
                    initDataType = access.getConfiguration().initDataTypes[0];
                    initData = getInitData(initDataType);
                    return access.createMediaKeys();
                }).then(test.step_func(function(mediaKeys) {
                    mediaKeySession = mediaKeys.createSession();
                    waitForEventAndRunStep('message', mediaKeySession, test.step_func(processMessage), test);
                    return mediaKeySession.generateRequest(initDataType, initData);
                })).catch(test.step_func(function(error) {
                    forceTestFailureFromPromise(test, error);
                }));
            }, 'Verify v2 events.');
        </script>
    </body>
</html>
